package com.example.mediacore.player;

import android.view.Surface;
import android.util.Log;

/**
 * 与JNI层严格匹配的Native播放器封装
 */
public class NativePlayer {
    private static final String TAG = "NativePlayer";

    // Native层AVPlayerCore实例指针（0表示无效）
    private long mNativePtr;
    // 状态变化监听器
    private OnStateChangeListener mStateListener;

    /**
     * 状态变化回调接口（使用PlayerState枚举）
     */
    public interface OnStateChangeListener {
        void onStateChanged(PlayerState state);
    }

    /**
     * 设置状态变化监听器
     */
    public void setOnStateChangeListener(OnStateChangeListener listener) {
        mStateListener = listener;
    }

    /**
     * JNI层状态回调入口（由JNI直接调用，接收int值并转换为枚举）
     */
    @SuppressWarnings("unused")
    private void onStateChanged(int nativeStateCode) {
        try {
            PlayerState state = PlayerState.fromNativeCode(nativeStateCode);
            if (mStateListener != null) {
                mStateListener.onStateChanged(state);
            }
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "Invalid native state code: " + nativeStateCode, e);
        }
    }

    /**
     * 构造方法：创建Native实例
     */
    public NativePlayer() {
        mNativePtr = nativeCreate();
        if (mNativePtr == 0) {
            Log.e(TAG, "Failed to create native instance");
        }
    }

    /**
     * 初始化播放器
     */
    public void init(String url, Surface surface) {
        Log.d(TAG, "init: url=" + url);
        if (mNativePtr == 0) {
            Log.e(TAG, "init failed: native instance is invalid");
            return;
        }
        if (url == null) {
            Log.e(TAG, "init failed: url is null");
            return;
        }
        nativeInit(mNativePtr, url, surface);
    }

    /**
     * 开始播放
     */
    public void start() {
        Log.d(TAG, "start");
        if (mNativePtr != 0) {
            nativeStart(mNativePtr);
        }
    }

    /**
     * 暂停播放
     */
    public void pause() {
        Log.d(TAG, "pause");
        if (mNativePtr != 0) {
            nativePause(mNativePtr);
        }
    }

    /**
     * 停止播放
     */
    public void stop() {
        Log.d(TAG, "stop");
        if (mNativePtr != 0) {
            nativeStop(mNativePtr);
        }
    }

    /**
     * 跳转到指定时间（微秒）
     */
    public void seekTo(long timeUs) {
        Log.d(TAG, "seek to: " + timeUs + "us");
        if (mNativePtr != 0) {
            nativeSeek(mNativePtr, timeUs);
        }
    }

    /**
     * 获取当前播放位置（微秒）
     */
    public long getCurrentPosition() {
        if (mNativePtr != 0) {
            return nativeGetPosition(mNativePtr);
        }
        return -1;
    }

    /**
     * 获取当前状态（返回PlayerState枚举）
     */
    public PlayerState getState() {
        if (mNativePtr == 0) {
            return PlayerState.ERROR;
        }
        int nativeCode = nativeGetState(mNativePtr);
        try {
            return PlayerState.fromNativeCode(nativeCode);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "getState failed: invalid native code", e);
            return PlayerState.ERROR;
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        Log.d(TAG, "release");
        if (mNativePtr != 0) {
            nativeRelease(mNativePtr);
            mNativePtr = 0;
            mStateListener = null;
        }
    }

    /**
     * 获取媒体信息
     */
    public MediaInfo getMediaInfo() {
        Log.d(TAG, "get media info");
        if (mNativePtr != 0) {
            return nativeGetMediaInfo(mNativePtr);
        }
        return null;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        if (mNativePtr != 0) {
            Log.e(TAG, "Resource leak: NativePlayer not released manually!");
            release();
        }
    }

    // JNI方法声明（与JNI层完全一致，无新增方法）
    private native long nativeCreate();
    private native void nativeInit(long ptr, String url, Surface surface);
    private native void nativeStart(long ptr);
    private native void nativePause(long ptr);
    private native void nativeStop(long ptr);
    private native void nativeSeek(long ptr, long timeUs);
    private native long nativeGetPosition(long ptr);
    private native int nativeGetState(long ptr);
    private native void nativeRelease(long ptr);
    private native MediaInfo nativeGetMediaInfo(long ptr);

    static {
        System.loadLibrary("playercore");
    }
}